package gl.web.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author Administrator
 * @Create at 2015-3-27 上午10:56:08
 * @Version 1.0
 *          <p>
 *          <strong>Features draft description.主要功能介绍</strong>
 *          </p>
 */
public class FileUtils {
	public static String readTextFromSrc(String file) throws IOException {
		InputStream in = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream(file);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		StringBuilder sb = new StringBuilder();
		String s;
		while ((s = br.readLine()) != null) {
			sb.append(s);
		}
		return sb.toString();
	}

	public static boolean appTextToFile(File file, String s) throws IOException {
		if (s == null || s.length() <= 0) {
			return false;
		}
		if (file == null) {
			return false;
		}
		if (!file.exists()) {
			if (!file.createNewFile()) {
				return false;
			}
		}
		try {
			FileWriter fw = new FileWriter(file, true);

			// 创建字符输出流对象
			BufferedWriter bf = new BufferedWriter(fw);
			// 创建缓冲字符输出流对象
			bf.append(s);
			bf.flush();
			bf.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;

	}

	public static String readUTF8FromFile(File file) throws IOException {
		if (!file.exists()) {
			return null;
		}
		InputStream in = new FileInputStream(file);
		BufferedInputStream bis = new BufferedInputStream(in);
		byte buffer[] = new byte[1024];
		;

		StringBuilder sb = new StringBuilder();
		int readCount = 0;
		while ((readCount = bis.read(buffer)) > 0) {
			sb.append(new String(buffer, 0, readCount, "UTF-8"));
		}
		bis.close();
		return sb.toString();
	}
}
